package map_and_set;

public class HashBuck {
    static class Node{
        public int key;
        public int value;
        public Node next;
        public Node(int key,int value){
            this.key = key;
            this.value = value;
        }
    }

    public Node[] array = new Node[10];
    public int usedSize;
    public static final double DEFAULT_LOAD_FACTOR = 0.75;

    public void push(int key,int value){
        int index = key % array.length;
        Node cur = array[index];
        while(cur != null){
            if(cur.key == key){
                cur.value = value;
                return;
            }
            cur = cur.next;
        }
        Node node = new Node(key,value);
        node.next = array[index];
        array[index] = node;
        usedSize++;
        if(doLoadFactor() >= DEFAULT_LOAD_FACTOR){
            resize();
        }
    }
    private double doLoadFactor(){
        return usedSize * 1.0 / array.length;
    }

    private void resize(){
        Node[] newArray = new Node[2 * array.length];
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            while(cur != null){
                int newIndex = cur.key % newArray.length;
                Node curN = cur.next;
                cur.next = newArray[newIndex];
                newArray[newIndex] = cur;
                cur = curN;
            }
        }
        array = newArray;
    }
    public int get(int key){
        int index = key % array.length;
        Node cur = array[index];
        while(cur != null){
            if(cur.key == key){
                return cur.value;
            }
            cur = cur.next;
        }
        return -1;
    }

}
